"""
PDF背景提取器 - Flask应用
只提取和展示PDF的背景部分，去除文字和图片
"""
from flask import Flask, request, jsonify, send_file, render_template
import os
from pdf_background_processor import PDFBackgroundProcessor

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024  # 50MB
app.config['UPLOAD_FOLDER'] = 'uploads'

# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

processor = PDFBackgroundProcessor()


@app.route('/')
def index():
    """主页"""
    return render_template('index.html')


@app.route('/upload_pdf', methods=['POST'])
def upload_pdf():
    """上传PDF并提取背景"""
    try:
        if 'pdf' not in request.files:
            return jsonify({'success': False, 'error': '没有上传文件'}), 400
        
        file = request.files['pdf']
        if file.filename == '':
            return jsonify({'success': False, 'error': '文件名为空'}), 400
        
        if not file.filename.lower().endswith('.pdf'):
            return jsonify({'success': False, 'error': '只支持PDF文件'}), 400
        
        # 保存上传的文件
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filepath)
        
        # 提取背景
        pages_data = processor.extract_background(filepath)
        
        return jsonify({
            'success': True,
            'pages': pages_data,
            'filename': file.filename
        })
        
    except Exception as e:
        print(f"❌ 处理PDF失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'error': str(e)}), 500


@app.route('/export_pdf', methods=['POST'])
def export_pdf():
    """导出纯背景PDF"""
    try:
        data = request.get_json()
        original_filename = data.get('filename', 'document.pdf')
        
        original_path = os.path.join(app.config['UPLOAD_FOLDER'], original_filename)
        
        if not os.path.exists(original_path):
            return jsonify({'success': False, 'error': '原始文件不存在'}), 404
        
        # 生成纯背景PDF
        output_pdf = processor.create_background_pdf(original_path)
        
        # 保存到临时文件
        output_path = os.path.join(app.config['UPLOAD_FOLDER'], 'background_' + original_filename)
        with open(output_path, 'wb') as f:
            f.write(output_pdf)
        
        return send_file(
            output_path,
            mimetype='application/pdf',
            as_attachment=True,
            download_name=f'background_{original_filename}'
        )
        
    except Exception as e:
        print(f"❌ 导出PDF失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'error': str(e)}), 500


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
